package com.invest.config;

import com.invest.vo.LoginUserVO;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.WebAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <p>注释</p>
 *
 * @author yuyizhao
 * @version v0.1 2016/3/8 Exp
 */
public class WebSecurityUtils {

    public static String getLoginError(HttpServletRequest request){

        HttpSession session = request.getSession(false);
        if (session != null) {
            AuthenticationException exception =
                    (AuthenticationException)request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);

            if(exception instanceof UsernameNotFoundException){
                return "用户不存在";
            }
            if(exception instanceof BadCredentialsException){
                return "用户或密码错误";
            }
            if(exception instanceof LockedException){
                return "帐户被锁";
            }
            if(exception instanceof DisabledException){
                return "帐户未启动";
            }
            if(exception instanceof AccountExpiredException){
                return "帐户已经过期";
            }
        }

        return null;

    }

    public static LoginUserVO getLoginUser(){
        Object user = SecurityContextHolder.getContext().getAuthentication() .getPrincipal();
        if(user instanceof LoginUserVO){
            return (LoginUserVO)user;
        }
        return null;
    }

}
